#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
登入授权相关页面
script name: views
Created on 2019/12/31 17:19 by PyCharm
@author: fujianjian
"""
from flask import flash, redirect, url_for, render_template, request, session, current_app
from flask_login import logout_user, login_required, login_user, current_user

from app.email import send_email
from ..models import User
from . import auth
from .forms import LoginForm, RegisterForm

from app import login_manager, db


@auth.route('/login', methods=['GET', 'POST'])
def login():
    """
    登入处理方法
    :return:
    """
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        print('the login user:', user)
        if user is not None and user.verify_password(form.password.data):
            login_user(user, form.remember_me.data)
            # session['current_user'] = user
            return redirect(request.args.get('next') or url_for('main.index'))
        flash('登入失败，无有效的用户名和密码')
    return render_template('auth/login.html', form=form)


# @login_required装饰定义保护路由，需要登入才能访问
@auth.route('/logout')
@login_required
def logout():
    """
    登出处理方法
    :return:
    """
    logout_user()
    flash('登出成功')
    return redirect(url_for('main.index'))


@auth.route('/register', methods=['GET', 'POST'])
def register():
    """
    注册处理方法
    :return:
    """
    form = RegisterForm()
    if form.validate_on_submit():
        user = User(email=form.email.data, username=form.username.data, password=form.password.data)
        db.session.add(user)
        db.session.commit()
        token = user.generate_confirmation()
        send_email(user.to, 'Confirm Your Account', 'auth/email/confirm',
                   token=token, user=user)
        flash('注册成功，确认邮件已经发送到邮箱,请激活账号')
        return redirect(url_for('auth.login'))

    return render_template('auth/register.html', form=form)


@auth.route('/confirm/<token>')
@login_required
def confirm(token):
    """
    确认账号的的视图函数
    :param token:
    :return:
    """
    if current_user.confirmed:
        return redirect(url_for('main.index'))
    if current_user.confirm(token):
        flash('You have confirmed Your account')
    else:
        flash('The confirmation link is invalid or has expired.')

    return redirect(url_for('main.index'))


@login_manager.user_loader
def load_user(user_id):
    print('the loader user_id:', user_id)
    user = User.query.get(int(user_id))
    print('the load user by get: ', user)
    user = user.query.filter(User.id == int(user_id)).first()
    print('the load user by filter', user)
    return user
